// packageUser/pages/envelop/envelop.js
import WxValidate from '../../../plugins/wx-validate/WxValidate';
import WalletService from '../../../service/WalletService';
import CommonService from '../../../service/CommonService';

const app = getApp();
const rules = {
  money: {
    required: true,
  },
  count: {
    required: true,
  }
};
const messages = {
  money: {
    required: '红包金额不能为空'
  },
  count: {
    required: '红包数量不能为空',
  }
};
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.walletService = new WalletService();
    this.commonService = new CommonService()
    if (options.id){
      this.setData({ orderId: options.id });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  /**发红包 */
  formSubmit: function(e){
    const _ =this;
    const wxValidate = new WxValidate(rules, messages);
    const envelop = e.detail.value;
    if (!wxValidate.checkForm(envelop)) {
      const error = wxValidate.errorList[0]
      this.setData({ errMsg: error.msg })
      return false
    }
    this.setData({ errMsg: '' });
    const {orderId} = this.data;
    envelop.orderId = orderId;
    this.walletService.spilt(envelop).then(function(res){
      if(res.status === 0){
        const { envelopScore } = app.globalData.setting;
        _.commonService.active(4).then(function (res) {
          if (res.status == 0) {
            wx.showModal({
              title: '红包发送成功',
              content: `你获得${envelopScore}枚救兵勋章`,
              showCancel: false,
              confirmText: '知道了',
              confirmColor: '#0f9bc1',
              success: function (res) {
                if (res.confirm){
                  wx.navigateBack();
                }
              }
            })
          }
        })
      }else{
        wx.showToast({
          title: res.messages,
          duration: 2000
        })
      }
    })
  }
})